<!--主页及其他非问题页面复用页头-->
<template>
  <el-header style="padding: 0">
    <el-menu
      :default-active="activeMenuIndex"
      class="el-menu-demo"
      mode="horizontal"
      @select="toMainPage"
    >
      <div class="logo-wrapper vertical-wrapper">
        <el-image :fit="'contain'" :src="require('@/assets/images/logo2.png')" />
      </div>
      <el-menu-item index="default">首页</el-menu-item>
      <el-menu-item index="follow">关注</el-menu-item>
      <div class="search-wrapper vertical-wrapper">
        <el-autocomplete
          v-model="searchInput"
          :placeholder="recommendQuestion"
          :fetch-suggestions="querySearchQuestion"
          :trigger-on-focus="false"
          :prefix-icon="Search"
          clearable
        >
          <template #append>
            <el-button @click="search">搜索</el-button>
          </template>
        </el-autocomplete>
      </div>
      <div class="vertical-wrapper">
        <el-button type="primary" :icon="Promotion" @click="askQuestion">
          提问
        </el-button>
      </div>
      <div class="vertical-wrapper">
        <div>
          <el-button :icon="BellFilled" link>消息</el-button>
          <el-button :icon="Comment" @click="toMessage" link>
            私信
          </el-button>
        </div>
      </div>
      <div class="vertical-wrapper">
        <el-dropdown>
          <el-avatar
            :src="
              avatarError
                ? '//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/default?t=' +
                  Math.random()
                : '//images.weserv.nl/?url=150.158.52.191:8080/HeadPortrait/' +
                  userId +
                  '?t=' +
                  Math.random()
            "
            @error="avatarError = !avatarError"
          />
          <template #dropdown>
            <el-dropdown-item @click="toPersonal">个人主页</el-dropdown-item>
            <el-dropdown-item @click="logOut">退出登录</el-dropdown-item>
          </template>
        </el-dropdown>
      </div>
    </el-menu>
    <el-dialog
      v-model="askDialogVisible"
      style="text-align: left"
      title="提问"
      width="600px"
    >
      <el-input
        v-model="askTitleTextArea"
        type="textarea"
        style="margin-bottom: 20px"
        :autosize="{ minRows: 1, maxRows: 3 }"
        placeholder="输入问题背景、条件等详细信息"
        resize="none"
      />
      <el-input
        v-model="askContentTextArea"
        type="textarea"
        style="margin-bottom: 20px"
        :autosize="{ minRows: 3, maxRows: 5 }"
        placeholder="写下你的问题，准确地描述问题更容易得到解答"
        resize="none"
      />
      <el-tag
        v-for="(tag, index) in myTopicTags"
        @close="closeTag(index)"
        style="margin: 0 10px"
        size="large"
        closable
      >
        {{ tag.value }}
      </el-tag>
      <el-autocomplete
        v-if="tagInputVisible"
        v-model="tagInput"
        ref="InputRef"
        style="width: 180px"
        :fetch-suggestions="querySearchTag"
        @keyup.enter="newTagConfirm"
        @blur="newTagConfirm"
      />
      <el-button @click="showTagInput" :icon="Plus" type="primary" v-else link
        >绑定话题</el-button
      >
      <el-row justify="end">
        <el-button type="primary" @click="questionCommit">发布问题</el-button>
      </el-row>
    </el-dialog>
  </el-header>
</template>

<script setup>
import { ref, toRef, watch } from "vue";
import {
  Search,
  Comment,
  BellFilled,
  Promotion,
  Plus,
} from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import { ElMessage, ElNotification } from "element-plus";
import axios from "axios";

const userId = JSON.parse(localStorage.getItem("user")).id;

const avatarError = ref(false),
  activeMenuIndex = ref("");

/* --------------------------- 跳转菜单 --------------------------- */
const router = useRouter(),
  emits = defineEmits(["change"]);

watch(
  () => router.currentRoute.value,
  (newRoute) => {
    console.log(newRoute.query);
    switch (newRoute.name) {
      case "mainPage":
        activeMenuIndex.value = newRoute.query.type || "default";
        break;
      case "QuestionDetail":
        console.log(newRoute.query.question_id)
        emits("setQuestionID", newRoute.query.question_id);
        break;
      case "searchPage":
        emits("searchInfoChange", newRoute.query);
        break;
      case "editAnswer":
        emits("idChange", newRoute.query);
        break;
      case "personal":
        emits("tab", newRoute.query);
        break; 
      case "other":
        emits("setOtherUser_id", newRoute.query.user_id)
        break;
    }
  },
  { immediate: true }
);

const toMainPage = (index) => {
  switch (index) {
    case "default":
      router.push({
        path: "/mainPage",
      });
      break;
    case "follow":
      router.push({
        path: "/mainPage",
        query: {
          type: "follow",
        },
      });
      break;
  }
  emits("change", {
    last: activeMenuIndex.value,
    current: index,
  });
};

const toPersonal = () => {
  activeMenuIndex.value = "";
  router.push({ path: "/Personal" });
};

const toMessage = () => {
  activeMenuIndex.value = "";
  router.push({ path: "/message" });
};

/* --------------------------- 提问对话框 --------------------------- */
const askDialogVisible = ref(false),
  tagInputVisible = ref(false),
  tagInput = ref(""),
  InputRef = ref(),
  askTitleTextArea = ref(""),
  askContentTextArea = ref(""),
  myTopicTags = ref([]),
  topicTags = ref([]);

const askQuestion = () => {
  askDialogVisible.value = true;
  axios.get("http://localhost:8080/topic/all").then((r) => {
    const resp = r.data;
    if (resp.status === 0) {
      topicTags.value = resp.data.map((tag) => {
        return {
          value: tag.topic_name,
          id: tag.topic_id,
        };
      });
    } else {
      ElMessage.error("话题资源加载失败，请检查网络");
    }
  });
};

const closeTag = (index) => {
  myTopicTags.value.splice(index, 1);
};

const newTagConfirm = () => {
  const INPUT = tagInput.value,
    TAGS = topicTags.value,
    LENGTH = TAGS.length;
  let id = undefined;
  for (let i = 0; i < LENGTH; i++) {
    if (TAGS[i].value === INPUT) {
      id = TAGS[i].id;
      break;
    }
  }
  if (id != null) {
    myTopicTags.value.push({
      value: tagInput.value,
      id: id,
    });
  }
  tagInputVisible.value = false;
  tagInput.value = "";
  toMainPage("default");
};

const showTagInput = () => {
  tagInputVisible.value = true;
};

const querySearchTag = (queryString, callback) => {
  const results = queryString
    ? topicTags.value
        .filter((tag) => {
          return (
            tag.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
          );
        })
        .filter((tag) => {
          return !myTopicTags.value.some((myTag) => myTag.value === tag.value);
        })
    : [];
  callback(results);
};

const questionCommit = () => {
  const MY_TAGS = myTopicTags.value;
  if (MY_TAGS == null || MY_TAGS.length === 0) {
    ElMessage.warning("问题至少绑定一个话题");
    return;
  }

  let id_list = "";
  MY_TAGS.forEach((tag) => {
    id_list += tag.id + " ";
  });

  axios
    .post(
      `http://localhost:8080/question/topic_id/list?topic_id_list=${id_list}`,
      JSON.stringify({
        user_id: userId,
        question_title: askTitleTextArea.value.trim(),
        question_content: askContentTextArea.value.trim(),
      }),
      {
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
    .then((r) => {
      const resp = r.data;
      if (resp.status === 0) {
        emits("add", resp.data);
        ElMessage.success("提交问题成功！");
        askDialogVisible.value = false;
      } else {
        ElMessage.error("提交问题失败，请检查网络连接是否正常");
      }
    })
    .catch((error) => {
      console.log(error.request.response);
      ElNotification.error("提交问题失败，请检查网络连接是否正常");
    });
};

/* --------------------------- 搜索问题 --------------------------- */
const questions = ref([]),
  searchInput = ref(""),
  recommendQuestion = ref("");

let flashRecommend;

const props = defineProps({
    searchType: {
      type: String,
      required: true,
      default: "question",
    },
  }),
  curSearchType = toRef(props, "searchType");

axios
  .get(`http://localhost:8080/question?current_id=${userId}`)
  .then((r) => {
    const resp = r.data;
    if (resp.status === 0) {
      questions.value = resp.data.map((q) => {
        return {
          value: q.question_title,
        };
      });
      const TEMP = questions.value;
      recommendQuestion.value =
        TEMP[Math.floor(Math.random() * TEMP.length)].value;
      flashRecommend = setInterval(() => {
        const TEMP = questions.value;
        recommendQuestion.value =
          TEMP[Math.floor(Math.random() * TEMP.length)].value;
      }, 6000);
    }
  })
  .catch((error) => {
    console.log(error.request.response);
  });

const querySearchQuestion = (queryString, callback) => {
  const results = queryString
    ? questions.value.filter((question) => {
        return (
          question.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        );
      })
    : questions.value;
  callback(results);
};

const search = () => {
  const INFO =
    searchInput.value.trim() === ""
      ? recommendQuestion.value
      : searchInput.value.trim();

  if (INFO === "") ElMessage.warning("搜索信息不能为空");
  else {
    let page = router.resolve({
      path: "/searchPage",
      query: {
        keyword: INFO,
        type: curSearchType.value,
      },
    });
    window.open(page.href, "_blank");
  }
};

/* --------------------------- 退出登录 --------------------------- */
const logOut = () => {
  localStorage.clear();
  router.push({
    path: "/",
  });
};
</script>

<style scoped>
.search-wrapper,
.logo-wrapper {
  width: 22%;
}
.vertical-wrapper {
  height: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: auto;
}
</style>
